Integrating RTK Query and createAsyncThunk in the Same Application
You can use both RTK Query and createAsyncThunk together in the same Redux Toolkit application. RTK Query excels at managing server state (data fetched from APIs), while createAsyncThunk is ideal for managing client-side async workflows such as authentication, file uploads, or complex business logic that doesn’t directly fit into RTK Query endpoints.
Use RTK Query: For CRUD operations, automatic caching, re-fetching, and synchronization with server data.
Use createAsyncThunk: For one-off async logic such as login flows, chained async operations, or updating local state based on multiple API responses.
1. Create API Slice with RTK Query: Use createApi to define endpoints for fetching and mutating data.
2. Define Async Logic with createAsyncThunk: Use thunks for side effects or complex async operations not suitable for RTK Query.
3. Combine Reducers and Middleware: Add both the RTK Query reducer and middleware in configureStore.
4. Use Auto-Generated Hooks and Thunks Together: You can dispatch thunks and use RTK Query hooks in the same component when needed.
This hybrid approach lets you benefit from RTK Query’s automatic caching for server data and the flexibility of thunks for complex, custom async logic. They coexist seamlessly in a single Redux store.